<template>
  <div class="consultation-container">
    <!-- 顶部区域 -->
    <div class="header">
      <div class="header-content">
        <div class="icon-wrapper">
          <i class="ivu-icon ivu-icon-md-medical custom-icon"></i>
        </div>
        <h2 class="welcome-text">智能问诊助手</h2>
        <p class="sub-text">请描述您的症状，我们将为您提供专业建议</p>
        <Button type="warning" @click="showTutorial = true" icon="ios-help-circle-outline" size="small" ghost>
          使用教程
        </Button>
      </div>
    </div>

    <!-- 教程弹窗 -->
    <Modal v-model="showTutorial" title="智能问诊助手使用教程">
      <div class="tutorial-content">
        <p><strong>1. 症状描述</strong></p>
        <p>在输入框中详细描述您的症状，建议包含以下信息：</p>
        <ul>
          <li>症状出现的时间和持续时长</li>
          <li>症状的具体表现和严重程度</li>
          <li>是否有其他不适或并发症</li>
          <li>是否服用过药物或进行过治疗</li>
        </ul>

        <p><strong>2. 发送消息</strong></p>
        <p>点击"发送"按钮或使用快捷键 Ctrl + Enter 发送您的症状描述。AI助手会为您提供专业的分析和建议。</p>

        <p><strong>3. 查看历史记录</strong></p>
        <p>您可以在顶部的下拉菜单中选择查看历史咨询记录，方便您回顾之前的问诊内容。</p>

        <p><strong>4. 生成病历</strong></p>
        <p>完成问诊后，您可以点击"生成病历"按钮，系统将为您生成一份完整的病历记录。</p>
      </div>
    </Modal>

    <!-- 咨询记录选择器 -->
    <div class="consultation-selector" v-if="consultationDates.length > 0">
      <Select v-model="selectedConsultationId" style="width: 100%" @on-change="selectConsultation">
        <Option v-for="consultation in consultationDates" 
                :key="consultation.id" 
                :value="consultation.id">
          {{ consultation.date.toLocaleString() }} - {{ consultation.firstMessage.substring(0, 30) }}...
        </Option>
      </Select>
    </div>

    <!-- 对话历史区域 -->
    <div class="chat-history" ref="chatHistory">
      <div v-for="(message, index) in chatHistory" :key="index" 
           :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
        <div class="message-content">
          <template v-if="message.type === 'ai' && message.isStreaming">
            <span v-for="(char, charIndex) in message.content" 
                  :key="charIndex" 
                  class="streaming-char">{{ char }}</span>
          </template>
          <template v-else>
            <div v-html="formatMessage(message.content)"></div>
          </template>
        </div>
        <div class="message-time">{{ message.time }}</div>
      </div>

      <!-- 添加等待提示 -->
      <div v-if="isLoading" class="message ai-message">
        <div class="message-content loading-message">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
          <div class="loading-text">AI正在思考中，请稍候...</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-section">
      <div class="input-wrapper">
        <textarea
          v-model="symptoms"
          class="symptom-input"
          placeholder="请详细描述您的症状，例如：
- 症状出现的时间和持续时长
- 症状的具体表现
- 是否有其他不适"
          rows="3"
          @keyup.enter.ctrl="startConsult"
        ></textarea>
      </div>
    </div>

    <!-- 底部按钮区域 -->
    <div class="button-group">
      <button 
        class="consult-btn primary"
        @click="startConsult"
        :disabled="isLoading"
      >
        <i class="ivu-icon ivu-icon-md-chatboxes"></i>
        发送
      </button>
      <button 
        class="consult-btn secondary"
        @click="generateMedicalRecord"
        :disabled="isLoading || !consultationId"
      >
        <i class="ivu-icon ivu-icon-md-clipboard"></i>
        生成病历
      </button>
    </div>
  </div>
</template>

<script>
import { sendConsultation } from '@/api/consultation'
import { generateMedicalRecord } from '@/api/medical-record'
import { getMessages, getRecentConsultations, getAllConsultations } from '@/api/chat'
import Cookies from 'js-cookie'

export default {
  name: 'MedicalConsultation',
  data() {
    return {
      symptoms: '',
      isLoading: false,
      chatHistory: [],
      currentStreamingMessage: null,
      consultationId: null,
      isLoadingHistory: false,
      allConsultations: {}, // 存储所有咨询记录
      consultationDates: [], // 存储咨询日期列表
      selectedConsultationId: null, // 当前选中的咨询ID
      showTutorial: false
    }
  },
  created() {
    this.loadAllConsultations()
  },
  methods: {
    async loadAllConsultations() {
      try {
        this.isLoadingHistory = true;
        console.log('开始加载所有咨询记录');
        const response = await getAllConsultations();
        console.log('获取咨询记录响应:', response);
        
        if (!response) {
          throw new Error('响应为空');
        }
        
        if (response.success) {
          if (!response.result) {
            console.warn('响应成功但result为空');
            this.allConsultations = {};
            this.consultationDates = [];
            this.$Message.info('暂无咨询记录');
            return;
          }
          
          this.allConsultations = response.result;
          console.log('成功获取咨询记录:', this.allConsultations);
          
          // 检查数据结构
          Object.entries(this.allConsultations).forEach(([id, messages]) => {
            console.log(`咨询ID ${id}:`, {
              messageCount: messages && messages.length || 0,
              firstMessage: messages && messages[0] || null
            });
          });
          
          if (Object.keys(this.allConsultations).length === 0) {
            console.log('没有找到任何咨询记录');
            this.$Message.info('暂无咨询记录');
            return;
          }
          
          // 获取所有咨询ID并按时间排序
          this.consultationDates = Object.entries(this.allConsultations)
            .map(([id, messages]) => {
              if (!Array.isArray(messages) || messages.length === 0) {
                console.warn(`咨询ID ${id} 的消息记录无效:`, messages);
                return null;
              }
              
              const firstMessage = messages[0];
              console.log(`处理咨询ID ${id} 的第一条消息:`, firstMessage);
              
              if (!firstMessage.createTime) {
                console.warn(`咨询ID ${id} 的第一条消息没有时间戳:`, firstMessage);
                return null;
              }
              
              return {
                id,
                date: new Date(firstMessage.createTime),
                firstMessage: firstMessage.content || '(无内容)'
              };
            })
            .filter(item => item !== null)
            .sort((a, b) => b.date - a.date);
          
          console.log('处理后的咨询日期:', this.consultationDates);
          
          if (this.consultationDates.length > 0) {
            console.log('选择最新的咨询记录:', this.consultationDates[0].id);
            this.selectConsultation(this.consultationDates[0].id);
          } else {
            console.log('没有有效的咨询记录');
            this.$Message.warning('没有找到有效的咨询记录');
          }
        } else {
          console.warn('API返回错误:', response);
          this.$Message.warning(response.message || '获取咨询记录失败');
        }
      } catch (error) {
        console.error('加载咨询记录失败:', error);
        this.$Message.error('加载咨询记录失败: ' + (error.message || '未知错误'));
      } finally {
        this.isLoadingHistory = false;
      }
    },
    selectConsultation(consultationId) {
      console.log('选择咨询记录:', consultationId);
      
      if (!consultationId || !this.allConsultations[consultationId]) {
          console.warn('无效的咨询ID或找不到对应的记录:', consultationId);
          this.$Message.warning('无法加载选中的咨询记录');
          return;
      }
      
      this.selectedConsultationId = consultationId;
      const messages = this.allConsultations[consultationId];
      
      console.log('原始消息列表:', messages);
      
      this.chatHistory = messages.map(msg => {
          if (!msg || typeof msg !== 'object') {
              console.warn('无效的消息格式:', msg);
              return null;
          }
          
          const time = msg.createTime 
              ? new Date(msg.createTime).toLocaleTimeString('zh-CN', {
                  hour: '2-digit',
                  minute: '2-digit'
              })
              : this.formatTime();
              
          return {
              content: msg.content || '',
              type: msg.type || 'user',
              time: time,
              isStreaming: false
          };
      }).filter(msg => msg !== null);
      
      console.log('处理后的聊天记录:', this.chatHistory);
      
      this.consultationId = consultationId;
      this.$nextTick(() => {
          this.scrollToBottom();
      });
    },
    formatTime() {
      return new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    },
    addMessage(content, type) {
      this.chatHistory.push({
        content,
        type,
        time: this.formatTime(),
        isStreaming: false
      });
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    scrollToBottom() {
      const chatHistory = this.$refs.chatHistory;
      chatHistory.scrollTop = chatHistory.scrollHeight;
    },
    async streamResponse(text) {
      const message = {
        content: '',
        type: 'ai',
        time: this.formatTime(),
        isStreaming: true
      };
      this.chatHistory.push(message);
      
      for (let i = 0; i < text.length; i++) {
        message.content += text[i];
        await new Promise(resolve => setTimeout(resolve, 50));
        this.scrollToBottom();
      }
      
      message.isStreaming = false;
    },
    async startConsult() {
      if (!this.symptoms.trim()) {
        this.$Message.warning('请输入症状描述');
        return;
      }
      this.isLoading = true;
      try {
        // 添加用户消息
        this.addMessage(this.symptoms, 'user');
        // 调用API
        const response = await sendConsultation({
          message: this.symptoms,
          history: this.chatHistory.map(msg => ({
            content: msg.content,
            type: msg.type
          }))
        });
        // 处理响应
        if (response.success && response.result) {
          // 保存consultationId
          this.consultationId = response.result.consultationId;
          // 直接添加AI回复内容
          this.addMessage(response.result.result, 'ai');
        } else {
          throw new Error(response.message || '请求失败');
        }
      } catch (error) {
        this.$Message.error('问诊请求失败，请稍后重试');
        console.error(error);
      } finally {
        this.isLoading = false;
        this.symptoms = '';
      }
    },
    async generateMedicalRecord() {
      if (!this.consultationId) {
        this.$Message.warning('请先完成问诊');
        return;
      }
      
      this.isLoading = true;
      try {
        const response = await generateMedicalRecord(this.consultationId);
        
        if (response.success && response.result) {
          this.$Message.success('病历生成成功');
          // 可选：刷新病历区或跳转
        } else {
          throw new Error(response.message || '生成病历失败');
        }
      } catch (error) {
        this.$Message.error('生成病历失败，请稍后重试');
        console.error(error);
      } finally {
        this.isLoading = false;
      }
    },
    formatMessage(content) {
      if (!content) return '';
      
      // 替换**文字**为加粗样式
      content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      
      // 将换行符转换为HTML换行
      content = content.replace(/\n/g, '<br>');
      
      return content;
    }
  }
}
</script>

<style scoped>
.consultation-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 30px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.icon-wrapper {
  width: 64px;
  height: 64px;
  background: linear-gradient(135deg, #1890ff, #0050b3);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.custom-icon {
  color: white;
  font-size: 32px;
}

.welcome-text {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.sub-text {
  color: #5c6b7c;
  font-size: 16px;
  margin: 0;
  line-height: 1.6;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  margin-bottom: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.message {
  margin-bottom: 20px;
  max-width: 85%;
}

.user-message {
  margin-left: auto;
}

.ai-message {
  margin-right: auto;
}

.message-content {
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 15px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.message-content :deep(strong) {
  color: #1890ff;
  font-weight: 600;
}

.user-message .message-content {
  background: linear-gradient(135deg, #1890ff, #0050b3);
  color: white;
}

.ai-message .message-content {
  background: white;
  color: #2c3e50;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-time {
  font-size: 12px;
  color: #8c9bab;
  margin-top: 4px;
  text-align: right;
}

.streaming-char {
  display: inline-block;
  animation: fadeIn 0.1s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(2px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.input-section {
  margin-bottom: 20px;
}

.input-wrapper {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 4px;
}

.symptom-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid transparent;
  border-radius: 10px;
  font-size: 15px;
  line-height: 1.6;
  resize: none;
  background: #ffffff;
  color: #2c3e50;
  transition: all 0.3s ease;
}

.symptom-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

.symptom-input::placeholder {
  color: #8c9bab;
  line-height: 1.6;
}

.button-group {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 20px;
}

.consult-btn {
  min-width: 120px;
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.consult-btn.primary {
  background-color: #2d8cf0;
  color: white;
  border: none;
}

.consult-btn.primary:hover {
  background-color: #2b85e4;
}

.consult-btn.secondary {
  background-color: #19be6b;
  color: white;
  border: none;
}

.consult-btn.secondary:hover {
  background-color: #18b566;
}

.consult-btn:disabled {
  background-color: #c5c8ce;
  cursor: not-allowed;
}

.consult-btn i {
  font-size: 16px;
}

@media (max-width: 640px) {
  .consultation-container {
    margin: 16px;
    padding: 20px;
    height: calc(100vh - 60px);
  }

  .welcome-text {
    font-size: 20px;
  }

  .sub-text {
    font-size: 14px;
  }

  .message {
    max-width: 95%;
  }

  .button-group {
    flex-direction: column;
  }

  .consult-btn {
    width: 100%;
    justify-content: center;
  }
}

/* 加载提示样式 */
.loading-message {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.loading-text {
  color: #8c9bab;
  font-size: 14px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #1890ff;
  border-radius: 50%;
  animation: typing 1s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.4s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.6s;
}

@keyframes typing {
  0%, 100% {
    transform: translateY(0);
    opacity: 0.3;
  }
  50% {
    transform: translateY(-5px);
    opacity: 1;
  }
}

.consultation-selector {
  margin-bottom: 20px;
  padding: 0 20px;
}

/* 教程内容样式 */
.tutorial-content {
  padding: 10px;
  line-height: 1.8;
}

.tutorial-content p {
  margin-bottom: 15px;
}

.tutorial-content ul {
  padding-left: 20px;
  margin-bottom: 15px;
}

.tutorial-content li {
  margin-bottom: 8px;
  color: #5c6b7c;
}

.tutorial-content strong {
  color: #2c3e50;
  font-size: 16px;
}
</style> 